package ms.mq.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

/**
 * Project Name: ms
 * File Name: MessageReciever
 * Package Name: ms.mq.listener
 * Date: 2018/6/11  8:55
 * Copyright (c) 2018, tianyul All Rights Reserved.
 * 消息监听
 */
@Configuration
public class MessageReceiver {
    @Value("rabbitmq.host")
    private String host;
    @Value("rabbitmq.userName")
    private String userName;
    @Value("rabbitmq.password")
    private String password;
    @Value("rabbitmq.virtualHost")
    private String virtualHost;

    @Value("rabbitmq.exchange")
    private String exchange;
    @Value("rabbitmq.queue")
    private String queue;
    @Value("rabbitmq.key")
    private String key;

    /**
     * 创建连接
     * @return
     */
    @Bean
    public ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setAddresses(host);
        connectionFactory.setUsername(userName);
        connectionFactory.setPassword(password);
        connectionFactory.setVirtualHost(virtualHost);
        connectionFactory.setPublisherConfirms(true); //必须要设置
        return connectionFactory;
    }

    @Bean
    @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
    //必须是prototype类型
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate template = new RabbitTemplate(connectionFactory());
        return template;
    }

    /**
     * 针对消费者配置
     * 1. 设置交换机类型
     * 2. 将队列绑定到交换机
     *
     *
     FanoutExchange: 将消息分发到所有的绑定队列，无routingkey的概念
     HeadersExchange ：通过添加属性key-value匹配
     DirectExchange:按照routingkey分发到指定队列
     TopicExchange:多关键字匹配
     */
    @Bean
    public TopicExchange topicExchange() {
        return new TopicExchange(exchange);
    }

    /**
     *队列1
     * @return
     */
    @Bean
    public Queue Queue() {
        return new Queue(queue, true); //队列持久
    }

    /**
     * 队列和key
     * @return
     */
    @Bean
    public Binding binding() {
        return BindingBuilder.bind(Queue()).to(topicExchange()).with(key);
    }

    /**
     * 消费指定队列的消息
     * @return
     */
    @Bean
    public SimpleMessageListenerContainer messageContainer() {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory());
        container.setQueues(Queue());
        container.setExposeListenerChannel(true);
        container.setMaxConcurrentConsumers(1);
        container.setConcurrentConsumers(1);
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL); //设置确认模式手工确认
        container.setMessageListener(new ChannelAwareMessageListener() {

            @Override
            public void onMessage(Message message, Channel channel) throws Exception {
                try {
                    byte[] body = message.getBody();
                    String json = new String(body);
                    JSONObject.toJavaObject(JSON.parseObject(json), Object.class);
                    System.out.println("receive apply msg : " +json);
                }catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); //确认消息成功消费
                }
            }
        });
        return container;
    }
}
